package com.ranlen.ems_vue.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Slf4j
public class LoginInterceptor  implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;
    RedisTemplate redisTemplate;

    public LoginInterceptor(StringRedisTemplate stringRedisTemplate,RedisTemplate redisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String token =(String) session.getAttribute("token");
        log.info("token信息：[{}]",token);

        if (Strings.isBlank(token)) {
            response.setStatus(401);
            response.sendRedirect("/ems_vue/404.html");
            return false;
        }

        //刷新token
        String key = stringRedisTemplate.opsForValue().get(token);
        stringRedisTemplate.expire(token,2, TimeUnit.HOURS);
        redisTemplate.expire(key,2,TimeUnit.HOURS);

        //放行
        return true;

    }
}

